package leetcode.code0756;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import leetcode.IDebug;

public class Solution implements IDebug {

	Map<String, List<Character>> map;

	public boolean pyramidTransition(String bottom, List<String> allowed) {
		map = new HashMap<>();
		for (int i = 0; i < allowed.size(); i++) {
			String all = allowed.get(i);
			String key = all.substring(0, 2);
			char val = all.charAt(2);
			map.computeIfAbsent(key, k -> new ArrayList<>()).add(val);
		}
		return py(bottom);
	}

	private boolean py(String bottom) {
		int len = bottom.length();
		if (len == 2) {
			return map.containsKey(bottom);
		}
		Map<Integer, List<Character>> part = new HashMap<>();
		for (int i = 0; i < len - 1; i++) {
			String cur = bottom.substring(i, i + 2);
			if (!map.containsKey(cur)) {
				return false;
			}
			part.put(i, map.get(cur));
		}
		char[] cs = new char[len - 1];
		if (this.build(0, part, len - 1, cs)) {
			return true;
		}
		return false;
	}

	private boolean build(int index, Map<Integer, List<Character>> part, int size, char[] cs) {
		if (index == size) {
			return this.py(new String(cs));
		}
		List<Character> me = part.get(index);
		for (int i = 0; i < me.size(); i++) {
			char cur = me.get(i);
			cs[index] = cur;
			if (this.build(index + 1, part, size, cs)) {
				return true;
			}
		}
		return false;
	}

	@Override
	public void debug4() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
